package com.skydroid.fpvplayerdemo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.skydroid.fpvplayer.*;
import java.nio.ByteBuffer;

public class MainActivityForJava extends AppCompatActivity {
    private FPVWidget fpvWidget;
    private View mapWidget;
    private FrameLayout switchVideoMapLayout;

    private LiveStreamHelper liveStreamHelper = new LiveStreamHelper();

    private MP4RecordHelper mp4RecordHelper = new MP4RecordHelper();

    private final LiveStreamListener liveStreamListener = new LiveStreamListener() {
        @Override
        public void onLiveStreamStatus(LiveStreamStatus status, long timestamp_us) {
            MyLogger.kLog().e("直播流状态：" + status + " " + timestamp_us);
        }
    };

    private boolean isLiveStart = false;

    private boolean isStartRecord = false;
    private Button btnRecordVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Settings settings = new Settings(getApplicationContext());
        // 去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        fpvWidget = findViewById(R.id.fpvWidget);
        mapWidget = findViewById(R.id.map);
        switchVideoMapLayout = findViewById(R.id.switch_video_map);
        btnRecordVideo = findViewById(R.id.btnRecordVideo);
        findViewById(R.id.btnUrl).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lastUrl = settings.getLastUrl();
                if (TextUtils.isEmpty(lastUrl)) {
                    lastUrl = Settings.C10;
                }
                InputUrlDialogFragment.createDialog("确定", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String url) {
                        if (TextUtils.isEmpty(url)) {
                            return;
                        }
                        settings.setLastUrl(url);
                        fpvWidget.setUrl(url);
                        fpvWidget.stop();
                        fpvWidget.start();
                    }

                }, "取消", new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {

                    }
                }, lastUrl).show(getSupportFragmentManager(), "action_url");
            }
        });

        findViewById(R.id.btnPushVideo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String lastPushUrl = settings.getLastPushUrl();
                String pb = isLiveStart ? "停止直播" : "开始直播";
                InputUrlDialogFragment.createDialog(pb, new InputUrlDialogFragment.ButtonOnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id, String url) {
                        if (TextUtils.isEmpty(url)) {
                            return;
                        }
                        if (isLiveStart) {
                            liveStreamHelper.stop();
                            isLiveStart = false;
                        } else {
                            settings.setLastPushUrl(url);
                            // 内部有重连机制，开发者只需要关注相关状态
                            liveStreamHelper.start(url);
                            isLiveStart = true;
                        }
                    }

                }, "取消", new InputUrlDialogFragment.ButtonOnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int id, String s) {

                    }
                }, lastPushUrl).show(getSupportFragmentManager(), "action_url");
            }
        });

        String url = settings.getLastUrl();
        // 使用硬解
        fpvWidget.setUsingMediaCodec(true);

        // 设置播放地址
        fpvWidget.setUrl(TextUtils.isEmpty(url) ? Settings.C10 : url);

        // 使用云卓播放器
        fpvWidget.setPlayerType(PlayerType.ONLY_SKY);

        // RTSP 流 TCP/UDP 连接
        fpvWidget.setRtspTranstype(RtspTransport.AUTO);

        mapWidget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFullVideo) {
                    switchVideoMap();
                }
            }
        });
        fpvWidget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFullVideo) {
                    switchVideoMap();
                }
            }
        });

        fpvWidget.setVideoDecoderCallBack(new VideoDecoderCallBack() {
            @Override
            public void onYUV(@NonNull ByteBuffer data, int width, int height, int pixel_format) {
                mp4RecordHelper.putYUV(data, width, height, pixel_format);
                liveStreamHelper.putYUV(data, width, height, pixel_format);
            }
        });

        // 设置直播流状态监听器
        liveStreamHelper.addListener(liveStreamListener);

        /**
         * 配置编码器相关属性
         */
        liveStreamHelper.setBitrate(1000000); // 比特率
        liveStreamHelper.setFrameRate(15); // 输出帧率
        liveStreamHelper.setVideoSize(640, 360); // 输出分辨率
        liveStreamHelper.setUseSoftEncoder(true); // true:软编码（X264），false:硬编码

        btnRecordVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isStartRecord) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        if (Environment.isExternalStorageManager()) {
                            startRecord();
                        } else {
                            startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION));
                        }
                    } else {
                        startRecord();
                    }
                } else {
                    mp4RecordHelper.stop(new MP4RecordHelper.MP4RecordCallBack() {
                        @Override
                        public void onRecordComplete(Exception error) {
                            if (error != null) {
                                MyLogger.kLog().e("停止录像失败:" + error);
                            }
                            isStartRecord = false;
                            switchRecordText();
                        }
                    });
                }
            }
        });

        // 开始播放
        fpvWidget.start();
    }

    private void startRecord() {
        checkStoragePermissions(1001, new PermissionsResultCallback() {
            @Override
            public void onGranted() {
                mp4RecordHelper.setBitrate(1500000); // 比特率
                mp4RecordHelper.setFrameRate(15); // 输出帧率
                mp4RecordHelper.setVideoSize(1280, 720); // 输出分辨率
                mp4RecordHelper.setUseSoftEncoder(true); // true:软编码（X264），false:硬编码
                String filePath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + System.currentTimeMillis() + ".mp4";
                Exception ret = mp4RecordHelper.start(filePath);
                if (ret == null) {
                    isStartRecord = true;
                    switchRecordText();
                } else {
                    MyLogger.kLog().e("开始录像失败:" + ret);
                }
            }

            @Override
            public void onDenied(String[] permissions) {
                // 没权限
            }

            @Override
            public void onError(Throwable e) {
                // 异常
            }
        });
    }

    private void switchRecordText() {
        if (isStartRecord) {
            btnRecordVideo.setText("停止录像");
        } else {
            btnRecordVideo.setText("开始录像");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止播放
        fpvWidget.stop();
        liveStreamHelper.removeListener(liveStreamListener);
        if (isLiveStart) {
            liveStreamHelper.stop();
            isLiveStart = false;
        }

        if (isStartRecord) {
            mp4RecordHelper.stop(new MP4RecordHelper.MP4RecordCallBack() {

                @Override
                public void onRecordComplete(Exception error) {
                    if (error != null) {
                        MyLogger.kLog().e("停止录像失败:" + error);
                    }
                    isStartRecord = false;
                    switchRecordText();
                }
            });
        }
    }

    private boolean isFullVideo = false;
    private void switchVideoMap() {
        if (isFullVideo) {
            // 设置交换图层后的宽高
            FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams) fpvWidget.getLayoutParams();
            fpvLayoutParams.width = PxUtils.dp2px(this, 240);
            fpvLayoutParams.height = PxUtils.dp2px(this, 135);
            fpvLayoutParams.gravity = Gravity.BOTTOM | Gravity.START;
            fpvWidget.setLayoutParams(fpvLayoutParams);
            FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams) mapWidget.getLayoutParams();
            mapLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            mapLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            mapWidget.setLayoutParams(mapLayoutParams);
            // 交换图层
            switchVideoMapLayout.removeView(fpvWidget);
            switchVideoMapLayout.addView(fpvWidget);
            isFullVideo = false;
        } else {
            // 设置交换图层后的宽高
            FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams) fpvWidget.getLayoutParams();
            fpvLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            fpvLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            fpvWidget.setLayoutParams(fpvLayoutParams);
            FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams) mapWidget.getLayoutParams();
            mapLayoutParams.width = PxUtils.dp2px(this, 240);
            mapLayoutParams.height = PxUtils.dp2px(this, 135);
            mapLayoutParams.gravity = Gravity.BOTTOM | Gravity.START;
            mapWidget.setLayoutParams(mapLayoutParams);
            // 交换图层
            switchVideoMapLayout.removeView(mapWidget);
            switchVideoMapLayout.addView(mapWidget);
            isFullVideo = true;
        }
    }

    /**
     * 检查存储权限
     * @param result
     */
    private void checkStoragePermissions(int requestCode, PermissionsResultCallback result) {
        PermissionManager.getInstance()
                .checkPermissions(this, requestCode, result,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance()
                .onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}



